//
//  AppDelegate.m
//  sinashebao
//
//  Created by  androidlongs on 2017/11/28.
//  Copyright © 2017年  androidlongs. All rights reserved.
//

#import "AppDelegate.h"
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "SINAStudentTabBarViewController.h"
#import "PTStuLSReleaseDetailViewController.h"
#import "PTStuLSPartJobDetailViewController.h"
#import "PTCoreDefine.h"

#import "WXApi.h"
#import "WXApiManager.h"

@interface AppDelegate ()<JPUSHRegisterDelegate,UIAlertViewDelegate>


@property(strong,nonatomic) NSDictionary *pushDict;
@property(strong,nonatomic) NSDictionary *msgDict;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   
    [WXApi registerApp:@"wx35768a01f369dc62"];
  
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // Optional
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    //参数三 0 (默认值)表示采用的是开发证书，1 表示采用生产证书发布应用
    [JPUSHService setupWithOption:launchOptions appKey:jpushKey
                          channel:@"app store"
                 apsForProduction:0
            advertisingIdentifier:advertisingId];
    
    
    if (launchOptions !=nil) {// 不是空 就是推送点击 否则是图标启动
        
        NSDictionary* remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        
        if ([[UIDevice currentDevice].systemVersion floatValue] < 10.0) {
            // iOS 10 不必走此方法
            [self reciveNotification:remoteNotification];// 处理推送跳转方法 详见下方
        }
        
    }

    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    //在这个方法里输入如下清除方法
    [application setApplicationIconBadgeNumber:0]; //清除角标
    [[UIApplication sharedApplication] cancelAllLocalNotifications];//清除APP所有通知消息
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"sinashebao"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                     */
                    DLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        DLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}
//竖屏限制
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    return UIInterfaceOrientationMaskPortrait;
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}
//实现注册APNs失败接口（可选）
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    DLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
            [self reciveNotificationAlertShow:userInfo];
        }
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    } // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
 
}
// APP 处于前台的时候 推送通知点击创建alertview  点击跳转方法和杀死 后台运行状态处理方法相同

-(void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    
    if (application.applicationState == UIApplicationStateActive) {
        // 如果是前台运行出现弹窗
        // 前台收到推送出现弹窗
        [self reciveNotificationAlertShow:userInfo];
    }else{
        // 处于后台 的点击
        [self reciveNotification:userInfo];
        
    }
    completionHandler(UIBackgroundFetchResultNewData);
}
/*
 基于iOS 6 及以下的系统版本，如果 App状态为正在前台或者点击通知栏的通知消息，那么此函数将被调用，并且可通过AppDelegate的applicationState是否为UIApplicationStateActive判断程序是否在前台运行。此种情况在此函数中处理：
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
}


- (void)reciveNotificationAlertShow:(NSDictionary*) dic{
    
    
    if (dic==nil) {
        return;
    }
    self.pushDict = dic;
    NSString *pushMsgType = [self.pushDict valueForKey:@"pushMsgType"];
    NSDictionary *aps = [dic valueForKey:@"aps"];
    //推送显示的内容
    NSString *content = [aps valueForKey:@"alert"];
    //badge数量
    //    NSInteger badge = [[aps valueForKey:@"badge"] integerValue];
    //播放的声音
    //    NSString *sound = [aps valueForKey:@"sound"];
    
    //生活服务推送处理
    
    if (pushMsgType!=nil && [pushMsgType isEqualToString:@"STUACCESSTASKMSG"])
    {
        [self lifeServiceReceiveNotificationWith:content];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息提示"message:[NSString stringWithFormat:@"%@",content] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"查看",nil];
        if (pushMsgType!=nil&&[pushMsgType isEqualToString:@"STULEAVELEVELMSG"]) {
            alert = [[UIAlertView alloc]initWithTitle:@"消息提示"message:[NSString stringWithFormat:@"%@",content] delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil,nil];
        }else if (pushMsgType!=nil&&[pushMsgType isEqualToString:@"TECPUBLISHSCORE"]) {
            alert = [[UIAlertView alloc]initWithTitle:@"消息提示"message:[NSString stringWithFormat:@"%@",content] delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil,nil];
        }
        
        [alert show];
    }
    
    
}

// APP杀死和后台时 推送点击的跳转处理

- (void)reciveNotification:(NSDictionary *)pushdic{
    // 获取当前停留的controler 进行push
    DLog(@"后台点击出");
    
    
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    DLog(@"alert dismiss");
    if (self.msgDict!=nil) {
        //创建通知
        NSNotification *notification =[NSNotification notificationWithName:@"jpushNotification" object:nil userInfo:self.msgDict];
        //通过通知中心发送通知
        [[NSNotificationCenter defaultCenter] postNotification:notification];
    }
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    DLog(@" button index=%ld is clicked.....", (long)buttonIndex);
    if (self.pushDict!=nil&&buttonIndex==1) {
        // 取得Extras字段内容
        NSString *pushMsgType = [self.pushDict valueForKey:@"pushMsgType"];
        //添加 字典，将label的值通过key值设置传递
        NSMutableDictionary *dict =[[NSMutableDictionary alloc]initWithObjectsAndKeys:pushMsgType,@"pushMsgType",nil];
        
        ////TECPUBLISHSCORE 老师发布成绩
        if (pushMsgType!=nil&&[pushMsgType isEqualToString:@"STULEAVELEVELMSG"]) {
            return;
        }else if (pushMsgType!=nil&&[pushMsgType isEqualToString:@"TECPUBLISHSCORE"]) {
            return;
        }
        else if (pushMsgType!=nil && [pushMsgType isEqualToString:@"STUACCESSTASKMSG"])
        {
            [self pushLifeServiceDetailPage];
        }
        
        if (pushMsgType!=nil&& [pushMsgType isEqualToString:@"TECCOURSESIGN"]){
            // 取得Extras字段内容
            NSString *pushMsgType = [self.pushDict valueForKey:@"pushMsgType"];
            NSString *syllabusuuid = [self.pushDict valueForKey:@"syllabusuuid"];
            NSString *syllabusacuuid = [self.pushDict valueForKey:@"syllabusacuuid"];
            NSString *signstarttime =[self.pushDict valueForKey:@"signstarttime"];
            
            NSString *lat = [self.pushDict valueForKey:@"lati"];
            NSString *lon = [self.pushDict valueForKey:@"lon"];
            
            NSString *msgContent = [self.pushDict valueForKey:@"msgcontent"];
            //添加 字典，将label的值通过key值设置传递
            dict =[[NSMutableDictionary alloc]initWithObjectsAndKeys:pushMsgType,@"pushMsgType",syllabusuuid,@"syllabusuuid",syllabusacuuid,@"syllabusacuuid",msgContent,@"msgContent",nil];
            if (lat!=nil) {
                [dict setObject:lat forKey:@"lat"];
            }
            if (lon!=nil) {
                [dict setObject:lon forKey:@"lon"];
            }
            if (signstarttime!=nil) {
                [dict setObject:signstarttime forKey:@"signstarttime"];
            }
            
        }
        self.msgDict = dict;
    }else{
        self.msgDict =nil;
    }
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if ([[url scheme] isEqualToString:@"wx35768a01f369dc62"]) {
        //微信
        return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    }
    else if([[url scheme] isEqualToString:@"tencent1106851585"])
    {
        //QQ
        [QQApiInterface handleOpenURL:url delegate:nil];
        
        if (YES == [TencentOAuth CanHandleOpenURL:url])
        {
            return [TencentOAuth HandleOpenURL:url];
        }
    }
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    if ([[url scheme] isEqualToString:@"wx35768a01f369dc62"]) {
        //微信
        return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    }
    else if([[url scheme] isEqualToString:@"tencent1106851585"])
    {
        //QQ
        [QQApiInterface handleOpenURL:url delegate:nil];
        
        if (YES == [TencentOAuth CanHandleOpenURL:url])
        {
            return [TencentOAuth HandleOpenURL:url];
        }
    }
    return YES;
}

-(void)lifeServiceReceiveNotificationWith:(NSString *)content
{
    NSInteger taskType =[[self.pushDict objectForKey:@"tasktype"] integerValue];
    
    if (taskType>=1 && taskType<=5 ) {
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息提示"message:[NSString stringWithFormat:@"%@",content] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"查看",nil];
        [alert show];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息提示"message:[NSString stringWithFormat:@"%@",content] delegate:self cancelButtonTitle:@"已读" otherButtonTitles:nil,nil];
        [alert show];
    }
}

-(void)pushLifeServiceDetailPage
{
    //生活服务接收通知
    DLog(@"推送内容为 dict === %@",self.pushDict);
    
    [self.tabVC setSelectedIndex:1];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kPT_Global_Notification_RefreshLifeServiceList object:nil];
    
    //生活服务TabBar被选中
    NSInteger taskType =[[self.pushDict objectForKey:@"tasktype"] integerValue];
    
    CXBaseNavViewController *vc = [self.tabVC.viewControllers objectAtIndex:1];
    
    if (taskType==1 || taskType ==2) {
        
        //被承接 （我的发布详情）
        PTStuLSReleaseDetailViewController * releaseDetailViewController = [[PTStuLSReleaseDetailViewController alloc]init];
        releaseDetailViewController.serviceUUID = [self.pushDict objectForKey:@"serviceuuid"];
        [releaseDetailViewController setHidesBottomBarWhenPushed:YES];
        [vc pushViewController:releaseDetailViewController animated:YES];
    }
    else if (taskType==3 || taskType == 4 || taskType ==5)
    {
        //发布者完成任务 (我的兼职详情)
        PTStuLSPartJobDetailViewController * partJobDetailViewController = [[PTStuLSPartJobDetailViewController alloc]init];
        partJobDetailViewController.missionUUID =  [self.pushDict objectForKey:@"serviceuuid"];
        [partJobDetailViewController setHidesBottomBarWhenPushed:YES];
        [vc pushViewController:partJobDetailViewController animated:YES];
    }
}

@end
